<template>
  <el-select
    v-model="pro_id"
    size="small"
    :remote-method="selPros"
    remote
    filterable
    style="width: 100%"
    placeholder="请选择项目名称"
    clearable
    @change="selChange"
    @focus="selPros"
  >
    <el-option
      v-for="item in pors"
      :key="item.key"
      :label="item.value"
      :value="item.key"
    />
  </el-select>
</template>

<script>
import { selPros, queryPro } from '@/api/project'

export default {
  name: 'ProSelect',
  props: {
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      pors: [],
      pro_id: null
    }
  },
  watch: {
    'pro_id': {
      handler(n, o) {
        if(this.pro_id && this.pro_id !== ''){
          this.queryPro()
        }
      },
      immediate: false
    }
  },
  created() {
    this.$set(this, 'pro_id', this.value)
  },
  methods: {
    selChange() {
      this.$emit('input', this.pro_id)
    },
    selPros(query, id) {
      let str = ''
      if (Object.prototype.toString.call(query) === '[object String]') str = query
      selPros({ name: str, id: id ? id : '' }).then(response => {
        this.pors = response.pros
      }).catch(err => {
        this.$message.error(err)
      })
    },
    queryPro() {
      this.$set(this, 'pors', [])
      queryPro({ id: this.pro_id }).then(response => {
        const info = {}
        info.key = response.pro.id
        info.value = response.pro.name
        this.pors.push(info)
      }).catch(err => {
        this.$message.error(err.msg)
      })
    }
  }
}
</script>

<style scoped>
</style>
